package cms.com.yh.servlet;

import cms.common.CodeMsg;
import cms.common.Result;
import cms.mager.domain.User;
import cms.mager.service.UserService;
import cms.mager.service.impl.UserServiceImpl;
import cms.util.HttpCharSet;
import cms.util.InvokeHttp;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 功能:
 * Author: yuhui
 * Date: 2021/4/8 17:31
 */
public class Serlvet_login extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpCharSet.charSet(req,resp);
        String service = req.getParameter("service");
        InvokeHttp.invokeReq(this,service,req,resp);
    }

    /**
    * 功能描述: 用户登录接口
    * @Author: yuhui  2021/4/8 17:59
    */
    public void login(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        Result<User> login = null;
        if(checkCode(req,resp)){
            String userName = req.getParameter("username");
            String userPwd = req.getParameter("password");
            UserService us = new UserServiceImpl();
            login = us.Login(userName, userPwd);
            if(login.getCode() == 200){
                req.getSession().setAttribute("user",login.getData());
                req.getRequestDispatcher("WEB-INF/view/main.jsp").forward(req,resp);
            }else{
                req.setAttribute("respData", CodeMsg.ERROR_USER_NAME_PWD.msg);
                req.getRequestDispatcher("index.jsp").forward(req,resp);
            }
        }else{
            //login = new Result(CodeMsg.ERROR_LOGIN_CODE);
            req.setAttribute("respData",CodeMsg.ERROR_LOGIN_CODE.msg);
            req.getRequestDispatcher("index.jsp").forward(req,resp);
        }
    }

    /**
     * 功能描述: 用户登出接口
     * @Author: yuhui  2021/4/8 17:59
     */
    public void loginout(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
        HttpSession session = req.getSession();
        session.invalidate(); //将session进行解绑
        resp.sendRedirect("index.jsp");
    }

    public boolean checkCode(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String code = req.getParameter("card");
        if(code.equals(req.getSession().getAttribute("code"))){
            return true;
        }else{
            return false;
        }
    }
}
